package org.codeart.juc.lock;

import java.util.concurrent.locks.ReentrantReadWriteLock;

public class ReentrantRWLockDemo {

    public static final ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock();

    public static final ReentrantReadWriteLock.WriteLock wLock = rwLock.writeLock();

    public static final ReentrantReadWriteLock.ReadLock rLock = rwLock.readLock();

    public static void main(String[] args) throws InterruptedException {
        // 读写锁之前是互斥的 读操作之间不互斥 写操作之间互斥
        new Thread(() -> {
            rLock.lock();
            try {
                System.out.println("子线程");
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            } finally {
                rLock.unlock();
            }
        }).start();

        Thread.sleep(1000);
        wLock.lock();
//        rLock.lock();
        try {
            System.out.println("主线程");
        } finally {
//            rLock.unlock();
            wLock.unlock();
        }
    }

}
